<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Base64 文件上传与下载</title>
</head>
<body>
<h2>文件上传</h2>
<input type="file" id="fileInput" />
<button onclick="uploadFile()">上传</button>

<h2>文件下载</h2>
<input type="text" id="fileNameInput" placeholder="输入文件名" />
<button onclick="downloadFile()">下载</button>

<script>
    // 上传文件
    function uploadFile() {
        var fileInput = document.getElementById('fileInput');
        var file = fileInput.files[0];
        if (!file) {
            alert('请选择一个文件');
            return;
        }

        var reader = new FileReader();
        reader.onload = function(e) {
            var base64 = e.target.result;
            sendBase64ToServer(base64Upload, file.name);
        };
        reader.onerror = function(err) {
            console.error('文件读取失败:', err);
        };
        reader.readAsDataURL(file);
    }

    function sendBase64ToServer(base64, fileName) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://127.0.0.1:8004/fileBase64Upload/upload', true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = function() {
            if (xhr.status === 200) {
                alert('文件上传成功！');
            } else {
                alert('文件上传失败！');
            }
        };
        xhr.send(JSON.stringify({ 'fileName': fileName, 'base64': base64Upload }));
    }

    // 下载文件
    function downloadFile() {
        var fileName = document.getElementById('fileNameInput').value;
        if (!fileName) {
            alert('请输入文件名');
            return;
        }

        // 使用FormData传递数据
        var formData = new FormData();
        formData.append('fileName', fileName);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://127.0.0.1:8004/fileBase64Down/download', true);
        xhr.setRequestHeader('Content-Type', 'multipart/form-data');
        xhr.onload = function() {
            if (xhr.status === 200) {
                var response = JSON.parse(xhr.responseText);
                var base64 = response.base64;
                var fileName = response.fileName;

                // 将Base64数据转换为文件并下载
                var link = document.createElement('a');
                link.href = 'data:application/octet-stream;base64,' + base64Upload;
                link.download = fileName;
                link.click();
                alert('文件下载成功！');
            } else {
                alert('文件下载失败：' + xhr.responseText);
            }
        };
        xhr.send(formData);
    }
</script>
</body>
</html>